<?php

namespace App\Http\Controllers;

use App\Library\Lock;
use App\Library\Logic\ShopUserLogic;
use App\Library\Requests\Base\BaseMobileRequest;
use App\Models\OpenIdModel;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class WechatServerSettingController extends Controller
{
    public function index()
    {
        if (request()->method() == 'GET') {
            $nonce = request()->input('nonce');
            $signature = request()->input('signature');
            $timestamp = request()->input('timestamp');

            $token = '86d55e70bc9bf04d6877c627227004fe';
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            if ($tmpStr == $signature) return request()->input('echostr');
            else return '';
        } else if (request()->method() == 'POST') {
            // 事件处理    关注/取消事件等
            $postArr = file_get_contents("php://input");
            $arr = simplexml_load_string($postArr, "SimpleXMLElement", LIBXML_NOCDATA);
            if (strtolower($arr->MsgType) == "event") {
                $toUser = $arr->ToUserName;
                $foUser = $arr->FromUserName;   // 用户openid
                $msgType = 'text';
                $createTime = time();
                $content = '欢迎关注异宠星球,<a href="' . request()->getSchemeAndHttpHost() . '/front/h5/bindMobile.html">点此链接绑定账号</a>';
                if (strtolower($arr->Event) == "subscribe") {//订阅
                    $temp = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>";
                    $temp = sprintf($temp, $foUser, $toUser, $createTime, $msgType, $content);
                    $openidInfo = [
                        'plateform' => 2,
                        'openid' => $arr->FromUserName->__toString(),
                        'type' => 'wx',
                        'is_follow' => 1,
                    ];
                    OpenIdModel::query()->updateOrInsert([
                        'plateform' => 2,
                        'openid' => $arr->FromUserName->__toString(),
                        'type' => 'wx',
                    ], $openidInfo);
                    echo $temp;
                } elseif (strtolower($arr->Event) == "unsubscribe") {   // 取消订阅
                    OpenIdModel::query()->where([
                        'plateform' => 2,
                        'openid' => $arr->FromUserName->__toString(),
                        'type' => 'wx',
                    ])->update(['is_follow' => 0]);
                    return '';
                }
            }
        }
    }

    public function mobileAuth(BaseMobileRequest $request)
    {
        return Lock::get(__CLASS__ . __FUNCTION__ . $request->mobile, function () use ($request) {
            $user = ShopUserLogic::findByWhere('user_mobile', $request->mobile);
            if (is_null($user)) return fail(433);
            $url = $request->getSchemeAndHttpHost() . '/v1/api/wechatServerSetting/wechatAuthBack';
            return success(sprintf(__('wechat.wx.url.step1'), __('wechat.mp.appId'), urlencode($url), $request->get('mobile')));
        });
    }

    public function wechatAuthBack(Request $request)
    {
        $user = ShopUserLogic::findByWhere('userMobile', $request->get('state'));
        if (!empty(OpenIdModel::query()->where([
            'type' => 'wx',
            'user_id' => $user->user_id,
        ])->value('openid'))) {
            return redirect($request->getSchemeAndHttpHost() . '/gzh/bindSuccessful.html?from=mpwx');
        }
        $url = sprintf(__('wechat.wx.url.step2'), __('wechat.gz.appId'), __('wechat.gz.secret'), $request->get('code'));
        $accessTokenInfo = json_decode(file_get_contents($url), true);
        //file_put_contents('./token.txt', json_encode($accessTokenInfo));
        if (!isset($accessTokenInfo['unionid'])) return fail(433);
        $unionId = $accessTokenInfo['unionid'];
        $openId = $accessTokenInfo['openid'];
        $wx = DB::table('open_id')
            ->where([
                'user_id' => $user->user_id,
                'type' => 'wx',
                'plateform' => 2,
            ])->first();
        if (!empty($wx)) {
            $wx->unionid = $unionId;
            $wx->openid = $openId;
            $wx->save();
        } else {
            $openData = [
                'user_id' => $user->user_id,
                'unionid' => $unionId,
                'openid' => $openId,
                'plateform' => 2,
                'type' => 'wx'
            ];
            OpenIdModel::query()->insert($openData);
        }
        return redirect($request->getSchemeAndHttpHost() . '/gzh/bindSuccessful.html?from=mpwx');
    }

    public function unbindWechat(Request $request)
    {
        $user = ShopUserLogic::findByWhere('userMobile', $request->get('state'));
        if (!empty(DB::table('open_id')
            ->where([
                'user_id' => $user->user_id,
                'type' => 'wx',
                'plateform' => 2,
            ])->value('openid'))) {
            DB::table('open_id')->where([
                'type' => 'wx',
                'plateform' => 2,
                'user_id' => $user->user_id,
            ])->delete();
        }
        return success();
    }

    public function followWechat(Request $request)
    {
        $tokenUrl = sprintf(__('wechat.gz.tokenUrl'), __('wechat.gz.appId'), __('wechat.gz.secret'));
        $tokenInfo = json_decode(file_get_contents($tokenUrl), true);
        $user = ShopUserLogic::findByWhere('userMobile', $request->get('mobile'));
        $user = DB::table('open_id')
            ->where([
                'user_id' => $user->user_id,
                'type' => 'wx',
                'plateform' => 2,
            ])->first();
        $data = [];
        if (!empty($user['openid'])) {
            $url = sprintf(__('wechat.gz.url'), $tokenInfo['access_token'], $user['openid']);
            $data = json_decode(file_get_contents($url), true);
        }
        return success(['is_gz' => $data['subscribe'] ?? 0]);
    }
}
